package logic

import (
	"fmt"
	"github.com/gogap/logs"
	"net/url"
	"time"
	"yundian/internel/app/models/paysetting"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/wxpay"
)

// 微信API调用
type WxApiCommon struct{}

func NewWxApiCommon() *WxApiCommon {
	return &WxApiCommon{}
}

// 小程序红包-发放
func (logic *WxApiCommon) HandleSendRedPacket(openid, mchBillNo string, amount int) (*wxpay.PayData, error) {
	wxConfig := NewSettingLogic().GetPaySetting()
	apiData := wxpay.NewPayData()
	apiData.Set("mch_billno", mchBillNo)
	apiData.Set("send_name", global.Const.Desc.UnifiedNameBody)
	apiData.Set("re_openid", openid)
	apiData.Set("total_amount", amount)
	apiData.Set("total_num", 1)
	apiData.Set("wishing", "恭喜发财，大吉大利")
	apiData.Set("act_name", "现金红包")
	apiData.Set("remark", "感谢您的参与！")
	apiData.Set("notify_way", "MINI_PROGRAM_JSAPI")
	apiData.Set("scene_id", "PRODUCT_2")
	if result, err := wxpay.ApiSendminiprogramhb(wxpay.NewCertPayClient(wxConfig), apiData, wxConfig); err != nil {
		return result, err
	} else {
		return logic.HandleSendRedPacketReceive(result, wxConfig), err
	}

	//result := wxpay.NewPayData()
	//p := `sendid=f8df9cd08746cc082c28bdda02c4f974f6cbcc309579cf9f24c4e1a0f6f7d82e&ver=8&sign=47ed13407edcee521a0d6893f78f0b43575e2146c3b5596e0437a765d156d2f52911ad2e3bc0f07e9394617ea52e42d0a52bdc646416f78724f5e50881d422e8&mchid=129913256&spid=1609227063`
	//result.Set("package", p)
	//return logic.HandleSendRedPacketReceive(result, wxConfig), nil
}

// 小程序红包-领取
func (logic *WxApiCommon) HandleSendRedPacketReceive(param *wxpay.PayData, wxConfig *paysetting.PaySetting) *wxpay.PayData {
	receiveData := wxpay.NewPayData()
	receiveData.Set("appId", wxConfig.AppId)
	receiveData.Set("timeStamp", fmt.Sprintf("%d", time.Now().Unix()))
	receiveData.Set("nonceStr", wxpay.NonceStr())
	receiveData.Set("package", url.QueryEscape(param.Get("package")))
	receiveData.Set("paySign", receiveData.MakePackageSign("wuxiangyunlianwuxiangyunlian3252", wxpay.SignTypeMD5))
	receiveData.Set("signType", wxpay.SignTypeMD5)

	logs.Info("HandleSendRedPacketReceive", receiveData.ToJson())
	return receiveData
}
